import { Channel, Article } from "@/types/data";
import { HomeAction } from "@/types/store";

type HomeState = {
  userChannels: Channel[]
  allChannels: Channel[]
  activeKey: number
  article: {
    [key: number]: {
      timestamp: number
      results: Article[]
    }
  }
}

const initialState: HomeState = {
  userChannels: [],
  allChannels: [],
  activeKey: 0,
  article: {}
}

export default function home(state=initialState, action: HomeAction) {
  if (action.type === 'home/saveUserChannels') {
    return {
      ...state,
      userChannels: action.payload
    }
  }
  if (action.type === 'home/saveAllChannels') {
    return {
      ...state,
      allChannels: action.payload
    }
  }
  if (action.type === 'home/changeAction') {
    return {
      ...state,
      activeKey: action.payload
    }
  }
  if (action.type === 'home/getArticleList') {
    const {channel_id, timestamp, results} = action.payload
    const oldResults = state.article[channel_id]?.results || []
    return {
      ...state,
      article: {
        ...state.article,
        [channel_id]: {
          timestamp,
          results: [...oldResults, ...results]
        }
      }
    }
  }
  if (action.type === 'home/saveNewArticles') {
    const {channel_id, timestamp, results} = action.payload
    return {
      ...state,
      article: {
        ...state.article,
        [channel_id]: {
          timestamp,
          results: results
        }
      }
    }
  }
  return state
}